/**

 * @author admin

 * 2014年7月9日

 */

package com.tmall.testgen.client.genfile.xls;

import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.excel.XlsDataSet;

import com.tmall.testgen.client.ClientDataCenter;
import com.tmall.testgen.common.bo.interact.back.DBInfo;


public class XlsUtil {

	private static XlsUtil instance =new XlsUtil();
	
	public static XlsUtil getInstace(){
		return instance;
	}
	
	
	public void backupData2Xls(String classNameWidthLocation,DBInfo dbInfo,String sqlSnap ) throws Exception{
		 Map<String,String> sqlMap=ClientDataCenter.getInstance().getSqlSnapMap(sqlSnap);
		 
		 if(sqlMap.size()==0)
			 return;
		 
		BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(dbInfo.getDriverClass());
         dataSource.setUrl(dbInfo.getUrl());
         dataSource.setUsername(dbInfo.getUserName());
         dataSource.setPassword(dbInfo.getPassword());
         
        
         
         
         
         IDatabaseConnection  connection= new DatabaseConnection(dataSource.getConnection()) {
				public void close() throws SQLException {

				}
			};
         
			DatabaseConfig config = connection.getConfig();
			config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new TestGenDataTypeFactory());
			
         QueryDataSet qd = new QueryDataSet(connection);  
         
         for(String tableName:sqlMap.keySet()){
        	 qd.addTable(tableName,sqlMap.get(tableName));  
         }
         
         XlsDataSet.write(qd,new FileOutputStream(classNameWidthLocation+".xls"));
         
         
	}
	


}
